﻿Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports FuncClasses
Imports System.IO
Imports System.Collections.ObjectModel
Imports System.Data
Public Class TablePDFExport
    Private _style As TableStyle = TableStyleTemplates.Gray_White
    Private _path As String = System.AppDomain.CurrentDomain.BaseDirectory() + "temp.pdf"
    Private _openfile As Boolean = True
    Private _showpagenumbers As Boolean = True
    Private Document As Document

    Public currentTableName As String

    Public Property FilePath As String
        Get
            Return _path
        End Get
        Set(value As String)
            _path = value
        End Set
    End Property

    Public Property OpenFileAfterCreation As Boolean
        Get
            Return _openfile
        End Get
        Set(value As Boolean)
            _openfile = value
        End Set
    End Property

    Public Property TableStyle As TableStyle
        Get
            Return _style
        End Get
        Set(value As TableStyle)
            _style = value
        End Set
    End Property

    Public Sub CreateTable(tablename As String, header As Collection(Of String), content As Collection(Of String), widths As Collection(Of Single))

        Dim writer As PdfWriter
        currentTableName = tablename
        _path = FilePath
        Document = New Document
        Dim mstream As New MemoryStream()
        Dim p1 As IElement
        Dim phrasecol As New Collection(Of IElement)
        Dim _event As New iTextPageTemplate(Me)

        If _showpagenumbers Then
            Document.SetMargins(36, 36, 36, cm_to_px(2))
            Try
                writer = PdfWriter.GetInstance(Document, mstream)
            Catch ex As Exception
                Exit Sub
            End Try
        Else
            Try
                writer = PdfWriter.GetInstance(Document, New FileStream(_path, FileMode.Create))
            Catch ex As Exception
                Exit Sub
            End Try
        End If

        Document.AddTitle(tablename)
        Document.Open()

        writer.PageEvent = _event

        pageHeader()

        Dim table As New PdfPTable(widths.ToArray)
        table.SpacingBefore = cm_to_px(1)
        table.HorizontalAlignment = Element.ALIGN_CENTER
        table.WidthPercentage = 90
        For Each s As String In header
            With TableStyle
                Dim c As New PdfPCell(New Phrase(s.ToString, TableStyle.FontHeader))
                c.BorderColorBottom = .HeaderBorderColors.Bottom : c.BorderColorTop = .HeaderBorderColors.Top : c.BorderColorLeft = .HeaderBorderColors.Left : c.BorderColorRight = .HeaderBorderColors.Right
                c.BorderWidthBottom = .HeaderBorderWidths.Bottom : c.BorderWidthTop = .HeaderBorderWidths.Top : c.BorderWidthLeft = .HeaderBorderWidths.Left : c.BorderWidthRight = .HeaderBorderWidths.Right
                c.BackgroundColor = .HeaderBackground
                table.AddCell(c)
            End With
        Next

        '### Content ###'
        Dim currentindex As Integer = -1
        Dim rowindex As Integer = -1
        For Each s In content
            currentindex += 1
            If currentindex Mod widths.Count = 0 Then
                rowindex += 1
            End If
            With TableStyle
                If (rowindex + 2) * widths.Count > content.Count Then
                    Dim c As New PdfPCell(New Phrase(s.ToString, .FontContent))
                    c.BorderColorBottom = .LastRowBorderColors.Bottom : c.BorderColorTop = .LastRowBorderColors.Top : c.BorderColorLeft = .LastRowBorderColors.Left : c.BorderColorRight = .LastRowBorderColors.Right
                    c.BorderWidthBottom = .LastRowBorderWidths.Bottom : c.BorderWidthTop = .LastRowBorderWidths.Top : c.BorderWidthLeft = .LastRowBorderWidths.Left : c.BorderWidthRight = .LastRowBorderWidths.Right
                    If .TakeLastRowBackgroundColorFromContentSeries Then
                        c.BackgroundColor = .GetCurrentCellBackground(rowindex)
                    Else
                        c.BackgroundColor = .LastRowBackground
                    End If
                    table.AddCell(c)
                Else
                    Dim c As New PdfPCell(New Phrase(s.ToString, .FontContent))
                    c.BorderColorBottom = .ContentBorderColors.Bottom : c.BorderColorTop = .ContentBorderColors.Top : c.BorderColorLeft = .ContentBorderColors.Left : c.BorderColorRight = .ContentBorderColors.Right
                    c.BorderWidthBottom = .ContentBorderWidths.Bottom : c.BorderWidthTop = .ContentBorderWidths.Top : c.BorderWidthLeft = .ContentBorderWidths.Left : c.BorderWidthRight = .ContentBorderWidths.Right
                    c.BackgroundColor = .GetCurrentCellBackground(rowindex)
                    table.AddCell(c)
                End If
            End With
        Next

        Document.Add(table)
        Document.Close()
        Try
            If _showpagenumbers Then
                Dim reader As New PdfReader(mstream.ToArray)
                Dim stamper As New PdfStamper(reader, New FileStream(_path, FileMode.Create))
                For i As Integer = 1 To reader.NumberOfPages
                    getHeaderTable(i, reader.NumberOfPages).WriteSelectedRows(0, -1, 35, cm_to_px(1.5), stamper.GetOverContent(i))
                Next
                stamper.Close()
            End If
        Catch ex As IOException
            MessageBox.Show("Die Datei kann nicht geschrieben werden. Schließen Sie offene Dokumente.", "Schreibfehler", MessageBoxButton.OK)
        End Try


        If _openfile Then
            Process.Start(FilePath)
        End If
    End Sub

    Public Function getHeaderTable(x As Integer, y As Integer) As PdfPTable
        Dim table As New PdfPTable(2)
        table.TotalWidth = 527
        table.LockedWidth = True
        table.DefaultCell.FixedHeight = 20
        table.DefaultCell.Border = Rectangle.NO_BORDER
        table.AddCell(" ")
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT
        table.AddCell(New Phrase(String.Format("Seite {0} von {1}", x, y), New Font(FontFactory.GetFont("Arial", 11))))
        Return table
    End Function

    Private Sub pageHeader()
        Document.Add(New Chunk(""))
        If True Then
            Dim temp As New Chunk(currentTableName)
            temp.Font = TableStyle.FontTitle
            Dim ph1 As New Paragraph(temp)
            'ph1.IndentationLeft = cm_to_px(1.8) - document.LeftMargin
            ph1.SpacingBefore = cm_to_px(0.7)
            ph1.Alignment = Element.ALIGN_CENTER
            Document.Add(ph1)
        End If
    End Sub

    Public Function cm_to_px(ByVal cm As Decimal) As Integer
        Return (cm / 2.54) * 72
    End Function
End Class

Public Class iTextPageTemplate
    Inherits PdfPageEventHelper
    Public Overrides Sub OnStartPage(writer As PdfWriter, document As Document)
        Header(document, writer)
    End Sub

    Public Sub New(ByVal parent As TablePDFExport)
        _parent = parent
    End Sub

    Private _parent As TablePDFExport
    Private Sub Header(document As Document, writer As PdfWriter)
        document.Add(New Chunk(""))
        '### Rechnungsnummer ###'
        If True Then
            Dim temp As New Chunk(_parent.currentTableName)
            temp.Font = _parent.TableStyle.FontHeader '_parent.font_arial_15_bold
            Dim ph1 As New Paragraph(temp)
            ph1.IndentationLeft = _parent.cm_to_px(1.8) - document.LeftMargin
            ph1.SpacingBefore = _parent.cm_to_px(0.7)
            ph1.SpacingAfter = _parent.cm_to_px(1)
            ph1.Alignment = Element.ALIGN_CENTER
            document.Add(ph1)
            Dim tbl As New PdfPTable({1})
            Dim cell As New PdfPCell
            cell.Border = Rectangle.NO_BORDER
            tbl.AddCell(cell)
            document.Add(tbl)
        End If
    End Sub
End Class